import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root*2+1;
        while(child<len){
            if(2*root+1+1<len&&elem[2*root+1]<elem[2*root+2]){
                child = root*2+2;
            }
            if(elem[root]<elem[child]){
                int tmp = elem[child];
                elem[child] = elem[root];
                elem[root] = tmp;
                root = child;
                child = root*2+1;
            }
            else break;
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while(child>0){
            if(elem[parent]>elem[child]){
                break;
            }
            else{
                swap(child,parent);
            }
            child = parent;
            parent = (child-1)/2;

        }
    }

    public boolean isFull() {
        if(usedSize==elem.length){
            return true;
        }
        return false;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0,usedSize);
        usedSize--;
        shiftDown(0,usedSize);
    }
    private void swap(int m,int n){
        int tmp = elem[m];
        elem[m] = elem[n];
        elem[n] = tmp;
    }

    public boolean isEmpty() {
        if(usedSize == 0){
            return true;
        }
        return false;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(!isEmpty()){
            return elem[0];
        }
        return -1;
    }
}